<template>
  <div style="overflow: hidden;width:100%;height:100%;" id="xGridParent">
    <vxe-grid ref='xGrid' v-bind="grid_options" @form-reset="formResetEvent">
      <template #toolbar_tools>
        <vxe-button @click="exportWord" icon="fa fa-arrow-down" class="export"></vxe-button>
      </template>
    </vxe-grid>

    <work-Order-Management-Form ref="workOrderManagementForm" @onSearch="onSearch"></work-Order-Management-Form>
    <!-- 其他的弹出组件可以写在这里面 -->

    <workOrderModel ref="workOrderModel" @onSearch="onSearch"></workOrderModel>
    <qualityEvaluation ref="qualityEvaluation" @onSearch="onSearch"></qualityEvaluation>
  </div>
</template>

<script>
import {reactive} from 'vue'
import {formModel, GridEvent} from './model/workOrderManagement-table.js'
import util from '@/utils/util'
import VXETable from "vxe-table";

export default {
  name: "workOrderManagement",
  components: {
    workOrderManagementForm: () => import("./components/workOrderManagementForm.vue"),
    workOrderModel: () => import("./components/workOrderModel1.vue"),
    qualityEvaluation: () => import("./components/qualityEvaluation.vue")
  },
  data() {
    return {
      size: "small",  //按钮尺寸大小//
      gdzt: '',
      etime: '',
      time: '',
      GridEvent: reactive(GridEvent),
      formModel: reactive(formModel),
      grid_options: {
        border: true, 				//表格边框//
        stripe: true, 				//行斑马色//
        showHeaderOverflow: true, //标头影藏//
        showOverflow: true,       //显示隐藏//
        keepSource: true,         //保持原始值的状�?�，被某些功能所依赖，比如编辑状态�?�还原数据等（开启后影响性能，具体取决于数据量）//
        id: 'full_edit_1',        //表格id，保证唯�?�?//
        height: 700,              //表格默认高度//
        rowId: 'sbbm',            //指定记录主键//
        rowConfig: {
          isCurrent: true,        //当鼠标点击列头时，是否要高亮当前�?//
          isHover: true,          //当鼠标移到列头时，是否要高亮当前列头//
        },
        columnConfig: {
          resizable: true         //每一列是否启用列宽调�?//
        },
        customConfig: {
          resizable: true,         //每一列是否启用列宽调�?//
          storage: true,          //是否启用 localStorage 本地保存，会将列操作状�?�保留在本地（需要有 id�?//
          // checkMethod: this.checkColumnMethod   //自定义列是否允许列�?�中的方法，该方法的返回值用来决定这�?列的 checkbox 是否可以选中//
        },
        printConfig: {
          columns: [              //指定�?//
            {field: 'sbbm'},
            {field: 'sbmc'},
            {field: 'yxzt'},
            {field: 'jlfs'},
            {field: 'sfsc'},
            {field: 'cap'},
            {field: 'sblx'},
            {field: 'sblxmc'},
            {field: 'num'},
            {field: 'standard'},
            {field: 'xh'},
            {field: 'cjmc'},
            {field: 'ccbm'},
            {field: 'ccTime'},
            {field: 'sjdhTime'},
            {field: 'cyDwmc'},
            {field: 'xmlxr'},
            {field: 'xmmc'},
            {field: 'xmbh'},
            {field: 'zlqx'},
            {field: 'yjccTime'},
            {field: 'xmdz'},
            {field: 'lxrPhone'},
            {field: 'lxTime'},
            {field: 'djhszt'},
            {field: 'cyDwbm'},
          ]
        },
        sortConfig: {             //排序配置�?//
          trigger: 'cell',        //触发方式（注：当多种功能重叠时，会同时触发）//
          remote: true            //�?有列是否使用服务端排序，如果设置�? true 则不会对数据进行处理//
        },
        filterConfig: {
          remote: true            //�?有列是否使用服务端筛选，如果设置�? true 则不会对数据进行处理//
        },
        pagerConfig: {            //分页配置�?//
          pageSize: 10,           //每页大小//
          pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],    //每页大小选项列表//
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],    //自定义布�?//
          background: true,        //带背景颜�?//
          fixed: true,            //固定在底部//
        },
        formConfig: {
          form: true,             //启用表单代理//
          size: 'small',          //尺寸//
          titleAlign: 'right',    //aa�?有项的标题对齐方式aa//
          titleWidth: '120',      //标题宽度aa//
          titleColon: true,       //是否显示标题冒号aa//
          collapseStatus: false,   //折叠状�?�aa//
          items: [                //项列表aa//
            {
              field: 'maintainUnitNo',
              title: '单位',
              span: 6,
              itemRender: {
                name: '$select',
                options: [],
                props: {placeholder: '---请输入---'},
                events: {change: this.gldwbmChangeEvent}
              }
            },
            {
              field: 'patrolTypeNo',
              title: '巡视类型',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请输入---', clearable: true}}
            },
            {
              field: 'patrolRoomName',
              title: '能源站名称',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '---请输入---'}}
            },
            {
              field: 'taskName',
              title: '巡视名称',
              span: 6,
              folding: true,
              itemRender: {name: '$input', props: {placeholder: '---请输入---'}}
            },
            {
              field: 'ptaskStatusNo',
              title: '工单状态',
              span: 6,
              folding: true,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请输入---', clearable: true}}
            },

            // { field: 'taskSourceNo', title: '工单来源', span: 6,folding: true, itemRender: { name: '$select', options: [], props: { placeholder: '---请输入---', clearable: true } } },
            {
              field: 'planStartTime',
              title: '计划开始时间',
              span: 6,
              folding: true,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '---请输入---'}}
            },
            {
              field: 'planEndTime',
              title: '至',
              span: 6,
              folding: true,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '---请输入---'}}
            },
            {
              span: 6,
              align: 'center',
              collapseNode: true,
              itemRender: {
                name: '$buttons',
                children: [{
                  props: {
                    type: 'submit',
                    content: '查询',
                    status: 'primary',
                    icon: 'fa fa-search'
                  }
                }, {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}}]
              }
            }
          ]
        },
        toolbarConfig: {          //工具栏配�?//
          //   buttons: [],          //左侧按钮列表//
          buttons: [
            // { buttonRender: { name: 'export', events: { click: this.exportWord } } }, // 导出
          ],
          refresh: true,          //刷新按钮配置//
          //   // import: true,        //导入按钮配置（需要设置import-config）//
          //   // print: true,         //打印按钮配置//
          //   // zoom: true,          //是否允许�?大化显示//
          custom: true,           //自定义列配置//
          slots: {
            buttons: 'toolbar_tools'    //按钮列表//
          }
        },
        proxyConfig: {
          seq: true, 		// 启用动�?�序号代理，每一页的序号会根据当前页数变�?//
          sort: true, 		// 启用排序代理，当点击排序时会自动触发 query 行为//
          filter: true, 	// 启用筛�?�代理，当点击筛选时会自动触�? query 行为//
          form: true, 		// 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为//
          // 对应响应结果 { result: [], page: { total: 100 } }//
          props: {
            result: 'data.records', 		//配置响应结果列表字段//
            total: 'data.total' 			//配置响应结果总页数字�?//
          },
          // 鍙帴鏀禤romise锛屽叿浣撳疄鐜拌嚜鐢卞彂鎸�//
          ajax: {
            // 当点击工具栏查询按钮或�?�手动提交指�? query或reload 时会被触�?//
            query: async ({page, sorts, filters, form}) => {
              //=====给表单项赋初始�??======//
              await GridEvent.initFormData(form);
              const queryParams = Object.assign({}, form)
              //处理排序条件//
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              //处理筛�?�条�?//
              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return GridEvent.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: 60, align: 'center', headerAlign: 'center'},
          {
            field: 'caozuo',
            title: '操作',
            minWidth: 120,
            showOverflow: false,
            showHeaderOverflow: false,
            filterMultiple: false,
            align: 'center',
            headerAlign: 'center',
            cellRender: {
              name: 'operation',
              events: {click1: this.editEvent, click2: this.workOrderModel, click3: this.qualityModel}
            },
            visible: true
          },
          {field: 'maintainUnitName', title: '单位', minWidth: 150, align: 'center', headerAlign: 'center',},
          {
            field: 'taskName',
            title: '巡视名称',
            minWidth: 150,
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'gdmc', events: {click: this.workOrderModel}}
          },
          {field: 'patrolTypeName', title: '巡视类型', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'patrolRoomName', title: '能源站名称', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'patrolTargetNames', title: '巡视对象名称', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'ptaskStatusName', title: '工单状态', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'planStartTime', title: '计划开始时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'planEndTime', title: '计划结束时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'patrolDescription', title: '巡视内容', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'sendTime', title: '派单时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'receiverTime', title: '接单时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'sceneTime', title: '到达现场时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'aEndTime', title: '巡视结束时间', minWidth: 150, align: 'center', headerAlign: 'center',},
          {field: 'remark', title: '备注', minWidth: 150, align: 'center', headerAlign: 'center',},
          {
            field: 'taskSourceNo', title: '数据来源', minWidth: 150, align: 'center', headerAlign: 'center',
            formatter({cellValue}) {
              return cellValue === '1' ? '平台创建' : 'app创建'
            }
          }
          // 0未回收 1 已回收
          // { field: 'cyDwbm', title: '产业单位编码',minWidth:150, align:'center',headerAlign:'center',},
        ],
        importConfig: {                         //导入配置�?//
          remote: true,                         //是否服务端导�?//
          importMethod: this.importMethod,      //只对 remote=true 有效，该函数用于自定义导入或服务端导入，返回 Promise//
          types: ['xlsx'],                      //导入的文件类型列�?//
          modes: ['insert']                     //导入数据的方�?//
        },
        exportConfig: {                         //导出配置�?//
          remote: true,                         //是否服务端导�?//
          exportMethod: this.exportWord,      //只对 remote=true 有效，该函数用于自定义导出或服务端导出，返回 Promise//
          types: ['xlsx'],                      //可�?�文件类型列�?//
          modes: ['current', 'selected', 'all'] //输出数据的方式列表，如果�? all，则会�?�过 proxy-config.ajax.queryAll 获取数据之后进行导出//
        },
        checkboxConfig: {                       //复�?�框配置�?//
          // labelField: 'id',                  //复�?�框显示的字段名，可以直接显示在复�?�框�?//
          reserve: true,                        //是否保留勾�?�状态，对于某些场景可能会用到，比如数据被刷新之后还保留之前选中的状态（�?要有 row-id�?//
          highlight: true,                      //高亮勾�?�行//
          range: true                           //�?启复选框范围选择功能（启用后通过鼠标在复选框的列内滑动�?�中或取消指定行�?//
        },
        editRules: {                            //校验规则配置�?//

        },
        editConfig: {                           //可编辑配置项//
          trigger: 'click',                     //触发方式//
          mode: 'row',                          //编辑模式//
          showStatus: true                      //只对 keep-source �?启有效，是否显示单元格新增与修改状�??//
        }
      }
    }
  },
  methods: {
    setTableHeight: function () { //高度自�?�应//
      const tableContainer = document.querySelector("#xGridParent");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        this.grid_options.columns[2].visible = false;
      } else {
        this.grid_options.columns[1].visible = false;
        this.grid_options.columns[13].visible = false;
        this.grid_options.columns[14].visible = false;
        this.grid_options.columns[15].visible = false;
        this.grid_options.columns[16].visible = false;
      }
      let edate = util.getRequestParms('edate')
      let date = util.getRequestParms('date')
      let gdzt = util.getRequestParms('gdzt')
      if (gdzt) {
        this.gdzt = gdzt
        this.$refs.xGrid._data.formData.ptaskStatusNo = gdzt
      }
      if (date && edate) {
        date = date + ' 00:00:00'
        edate = edate + ' 23:59:59'
        this.time = date
        this.etime = edate
        this.$refs.xGrid._data.formData.planStartTime = date
        this.$refs.xGrid._data.formData.planEndTime = edate
        let columns2
        this.$nextTick(() => {
          columns2 = this.$refs.xGrid.getColumns()
        })
        setTimeout(() => {
          // 将指定列设置为隐藏状态
          columns2.forEach(column => {
            if (['caozuo'].includes(column.property)) {
              column.visible = false
            } else if ('checkbox' == column.type) {
              column.visible = false
            }
          })
          if (this.$refs.xGrid) {
            this.$refs.xGrid.refreshColumn()
          }

        }, 100)
      }
    },
    formResetEvent({data}) {
      let datatime = new Date()
      if (this.time) {
        data['planStartTime'] = this.time
        data['planEndTime'] = this.etime
      } else {
        data['planStartTime'] = GridEvent.timeformat(datatime, 0, 'start')
        data['planEndTime'] = GridEvent.timeformat(datatime, 0, 'end')
      }

      data['ptaskStatusNo'] = this.gdzt
    },
    tBizcEneryEquipFormCloseEvent(reload) {  //form表单编辑窗口关闭事件//
      formModel.closeDialogEvent(reload, this.$refs.xGrid)
    },
    editEvent(row) {    //编辑事件//
      // const rows = this.$refs.xGrid.getCheckboxRecords(true);
      this.$refs.workOrderManagementForm.showDialog(true, row)
    },
    workOrderModel(row, bool) {
      this.$refs.workOrderModel.showDialog(row, bool)
    },
    qualityModel(row) {
      this.$refs.qualityEvaluation.showDialog(row)

    },
    deleteEvent() {  //删除事件//
      const rows = this.$refs.xGrid.getCheckboxRecords(true);
      if (rows) {
        GridEvent.deleteEvent(rows, this.$refs.xGrid);
      }
    },
    onSearch() {
      this.$refs.xGrid.commitProxy('query')
    },
    exportWord() {//导出事件
      // alert('导出')
      GridEvent.exportXls(this.$refs.xGrid);
    },
    handlePreview(info) {//模板导入
      console.log(info, 'iiiiiii');
      // GridEvent.exportXls(info);
      // let formData = new FormData();
      // formData.append("file",info.file);
      // formData.append("type","bzyhk");
      // SupportpersonnelApi.importXls(formData).then(res=>{
      //   antd.message.success(res)
      // }).catch(err=>{
      //   console.log(err)
      // })
      // GridEvent.exportXls(this.$refs.xGrid);
    },
    downloadXls() {
      window.open(process.env.VUE_APP_APP_API + '/equip/export/downloadTemplate')
      console.log(process.env.VUE_APP_APP_API + '/equip/export/downloadTemplate', '地址');
    },
    gldwbmChangeEvent(value) {
      GridEvent.gldwbmChangeEvent(this.$refs.xGrid, value)
    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(function () {
      // this.setTableHeight();
      GridEvent.getOptionData_gldw(this.$refs.xGrid)
      GridEvent.getOptionData_taskTypeNo(this.$refs.xGrid)
      // GridEvent.getOptionData_taskSource(this.$refs.xGrid)
      GridEvent.getOptionData_taskStatus(this.$refs.xGrid)
      this.setReadModel()
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.setTableHeight);
  },
}
VXETable.renderer.add('operation', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <div style="display:flex;flex-wrap:wrap;">
        <el-button disabled={row.ptaskStatusNo === '0' ? false : true}
                   type={row.ptaskStatusNo === '0' ? 'primary' : 'info'} size="small"
                   style={"margin:4px 0 4px 0;width:100px;"} onClick={
          () => {
            events.click1(params)
          }
        }>派单
        </el-button>
        <el-button disabled={row.ptaskStatusNo === '0' ? true : false}
                   type={row.ptaskStatusNo === '0' ? 'info' : 'primary'} size="small"
                   style="margin:0 0 4px 0;width:100px;" onClick={
          () => {
            events.click2(params, false)
          }
        }>过程监视
        </el-button>
        <el-button disabled={row.ptaskStatusNo == '30' ? false : true}
                   type={row.ptaskStatusNo === '30' ? 'primary' : 'info'} size="small"
                   style="margin:4px 0 4px 0;width:100px;" onClick={
          () => {
            events.click2(params, true)
          }
        }>质量评价
        </el-button>
      </div>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('export', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    const isRead = util.isReadModel()
    if (isRead) {
      return [
        <vxe-button icon="fa fa-arrow-down" content="导出" onClick={
          () => {
            events.click(button)
          }
        }></vxe-button>
      ]
    }
  }
})

VXETable.renderer.add('gdmc', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    const isRead = util.isReadModel()
    if (isRead) {
      return [
        <a style="color:#0000FF;cursor: pointer;" onClick={() => events.click(params)}>{row.taskName}</a>
      ]
    } else {
      return [
        <span>{row.taskName}</span>
      ]
    }
  },
})
</script>

<style scoped>
.upload-demo {
  display: inline;
  margin-left: 10px;
}

.export {
  color: var(--font-color) !important;
  border-color: var(--font-color) !important;
  background-color: var(--button-background-color) !important;
  border-radius: 5% !important;
  margin-left: 0.2em !important;
  padding: 0 0.5em !important;
  min-width: 30px;
  width: 32px !important;
  height: 32px !important;
  float: right;
}
</style>

